import DTO.People;
import DTO.Student;
import DTO.userinfomation;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.io.IOException;

@WebServlet(urlPatterns = {"/login/dgut"})
public class Servlet1 extends HttpServlet {
    private static final String URL = "jdbc:h2:~/jpa-demo-db;MODE=MYSQL;DB_CLOSE_DELAY=-1";
    private static final String NAME = "sa";
    private static final String PASSWORD = "sa";
    private static final EntityManagerFactory entityManagerFactory;
    private static final String PERSISTENCE_UNIT_NAME = "MyJPADemoPU";

    static {
        entityManagerFactory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
    }

    private EntityManager getEntityManager() {
        return entityManagerFactory.createEntityManager();
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

       // System.out.print("--------------------------------------------------------------!!!!!!!!!!------------------------------------------------------------------------");
        String string1 = null;
        String string2 = null;

        String token = req.getParameter("token");
        List<NameValuePair> form = new ArrayList<>();
        form.add(new BasicNameValuePair("token", token));
        form.add(new BasicNameValuePair("appid", "javaee"));
        form.add(new BasicNameValuePair("appsecret", "b3b52e43ccfd"));
        form.add(new BasicNameValuePair("userip", req.getLocalAddr()));
        HttpPost httppost_1 = new HttpPost("https://cas.dgut.edu.cn/ssoapi/v2/checkToken");//检查token
        UrlEncodedFormEntity uefEntity_1;
         // 创建默认的httpClient实例.
       try (CloseableHttpClient httpclient_1 = HttpClients.createDefault()) {
            uefEntity_1 = new UrlEncodedFormEntity(form, "UTF-8");
            httppost_1.setEntity(uefEntity_1);
            try (CloseableHttpResponse response_1 = httpclient_1.execute(httppost_1)) {
                HttpEntity entity_1 = response_1.getEntity();
                if (entity_1 != null) {
                    string1= EntityUtils.toString(entity_1, "UTF-8");
                }
            }
        }



        Jsonb json = JsonbBuilder.create();
        People people = json.fromJson(string1,People.class);

        String openid1=people.getOpenid();
        String access_token1=people.getAccess_token();
        List<NameValuePair> form1= new ArrayList<>();

        form1.add(new BasicNameValuePair("access_token", access_token1));
        form1.add(new BasicNameValuePair("openid", openid1));

        HttpPost httppost_2 = new HttpPost("https://cas.dgut.edu.cn/oauth/getUserInfo");//获取用户基本信息
        UrlEncodedFormEntity uefEntity_2;
        // 创建默认的httpClient实例.
        try (CloseableHttpClient httpclient_2 = HttpClients.createDefault()) {
            uefEntity_2 = new UrlEncodedFormEntity(form1, "UTF-8");
            httppost_2.setEntity(uefEntity_2);
            try (CloseableHttpResponse response_2 = httpclient_2.execute(httppost_2)) {
                HttpEntity entity_2 = response_2.getEntity();
                if (entity_2 != null) {
                    string2= EntityUtils.toString(entity_2, "UTF-8");
                }
            }
        }
        HttpSession session = req.getSession(true);
        Jsonb json_student=JsonbBuilder.create();
        Student student=json_student.fromJson(string2,Student.class);
        String img_default = "default.jpg";
        String username_new = student.getUsername();
        String password_new = "123456";
        String phone_new = "null";

        int flag = 0;
        try{
            Connection conn = DriverManager.getConnection(URL,NAME,PASSWORD);
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("select  * from USERINFOMATION");
            while(rs.next()){
                if(student.getUsername().equals(rs.getString("USERNAME"))){//数据库里有这个人的信息
                    flag = 1;
                    Map<String,String>user_map1 = new HashMap<>();
                    user_map1.put("username",rs.getString("USERNAME"));
                    user_map1.put("password",rs.getString("PASSWORD"));
                    user_map1.put("phone",rs.getString("PHONE"));
                    user_map1.put("img",rs.getString("IMG"));
                    session.setAttribute("USER",user_map1);//把其信息打包进对应的session
                    break;
                }
            }
            if(flag == 0){//数据库中没这个人的信息
                EntityManager em = getEntityManager();
                EntityTransaction tx = em.getTransaction();
                try {
                    userinfomation user = new userinfomation(username_new,password_new,phone_new,img_default);
                    tx.begin();
                    em.persist(user);
                    tx.commit();
                    Map<String,String>user_map2 = new HashMap<>();//把其信息打包进对应的session
                    user_map2.put("username",user.getUsername());
                    user_map2.put("password",user.getPasswd());
                    user_map2.put("phone",user.getPhone());
                    user_map2.put("img",user.getImg());
                    session.setAttribute("USER",user_map2);
                } catch (Exception e) {
                    throw new ServletException(e);
                } finally {
                    em.close();
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            resp.sendRedirect("error.html");
        }
        resp.sendRedirect("http://localhost:8080/user.jsp");
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}






